package it.softphone.commons.spring.config;


import it.softphone.commons.exception.NullParameterException;
import it.softphone.commons.service.LogAware;
import it.softphone.commons.service.config.ConfigurationServiceFactory;
import it.softphone.commons.spring.ApplicationConfig;

import java.net.URISyntaxException;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.springframework.config.java.support.ConfigurationSupport;

public class BaseConfigSupport extends ConfigurationSupport implements LogAware {
	public static final String DEFAULT_CONFIG_PROPERTIES = "baseConfig.properties";


	/**
	 * 
	 * @param beanName
	 * @param prefix
	 * @return
	 */
	public static org.apache.commons.configuration.Configuration getConfig( String beanName, String prefix ) {
    	Configuration conf = null;
    	
    	if( beanName == null ) beanName = "baseConfig";
    	
    	try {
    		
    		conf = ApplicationConfig.getBean(Configuration.class, beanName);
    		
    	}
    	catch( Throwable e ) {
			final String configUri = String.format("classpath:%s.properties", beanName);

			logger.warn( String.format("config bean named [%s] not found. try to load from [%s]", beanName, configUri));

			try {
				conf = ConfigurationServiceFactory.getConfigurationService( configUri );
			} catch (ConfigurationException e1) {
	    		logger.warn( String.format("config bean from uri [%s] not found. null is returned!", configUri));
	    		return null;
			}		
    	
    		
    	}
		if( prefix != null && prefix.length()>0 ) {
			conf = conf.subset(prefix);
		}
		return conf;
	}
	
	/**
	 * 
	 * @param resourceName
	 * @return
	 * @throws ConfigurationException
	 */
	public org.apache.commons.configuration.Configuration getBaseConfig( java.net.URI uri ) throws ConfigurationException {
		if( null==uri ) throw new NullParameterException("uri");
		
		org.apache.commons.configuration.Configuration conf = ConfigurationServiceFactory.getConfigurationService( uri );
		
		return conf;
		
	}
	
	/**
	 * 
	 * @return
	 * @throws ConfigurationException
	 */
	public org.apache.commons.configuration.Configuration getBaseConfig() throws ConfigurationException {
		try {
			return getBaseConfig( new java.net.URI( "classpath:".concat(DEFAULT_CONFIG_PROPERTIES) ) );
		} catch (URISyntaxException e) {
			throw new ConfigurationException(e);
		}
	}

}
